package com.coordinator.test;

import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;

/**
 * Created by Administrator on 2016/12/1.
 */

public class MyBehavior extends CoordinatorLayout.Behavior<Button>{
    private int width;

    MyBehavior(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        DisplayMetrics display = context.getResources().getDisplayMetrics();
        width = display.widthPixels;
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, Button child, View dependency) {
        return dependency instanceof TempView;
    }

    int nDependencyX;
    int nDependencyY;
    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, Button child, View dependency) {
        if(nDependencyX > 0 && nDependencyY > 0)
        {
            int top = dependency.getTop();
            int left = dependency.getLeft();

            int x = left - nDependencyX;
            int y = top - nDependencyY;
            setPosition(child, x, y);
            nDependencyX = dependency.getLeft();
            nDependencyY = dependency.getTop();
            return true;
        }
        else {
            nDependencyX = dependency.getLeft();
            nDependencyY = dependency.getTop();
        }
        return false;
    }

    private void setPosition(View v, int x, int y)
    {
        CoordinatorLayout.MarginLayoutParams layoutParams = (CoordinatorLayout.MarginLayoutParams)v.getLayoutParams();
        layoutParams.leftMargin = v.getLeft() - x;
        layoutParams.topMargin = v.getTop() + y;
        v.setLayoutParams(layoutParams);
    }
}
